package com.wx.spring.ioc.parsing;

import com.wx.spring.exception.XmlException;
import com.wx.spring.ioc.rules.IocXmlRules;
import com.wx.spring.utils.MyStringUtils;
import com.wx.spring.utils.ScanUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.dom4j.DocumentException;
import org.dom4j.Element;

import java.util.List;

/**
 * @author wx
 * @Description: 解析xml资源中的扫描
 * @date 2019/1/11 001113:49
 */
public class ParsingResourcesXmlScanning implements ParsingResources {

    /**
     * @param contextConfigLocation
     * @description: 解析xml component-scan扫描包路径下的注解对象到instanceSet容器中
     * @author: wx
     * @date: 2019/1/11 0011
     * @return: void
     */
    @Override
    public void parsingContent(String contextConfigLocation) throws DocumentException {
        List<Element> elementsList = getXmlElements(contextConfigLocation);
        if (CollectionUtils.isEmpty(elementsList)) {
            return;
        }
        try {
            for (Element element : elementsList) {
                //如果xml元素类型是扫描注解component-scan
                if (IocXmlRules.SNAN_RULE.getType().equals(element.getName())) {
                    //获取扫描包路径
                    String packageName = element.attributeValue(IocXmlRules.SNAN_RULE.getName());
                    if (MyStringUtils.isBlank(packageName)) {
                        throw new XmlException("请正确设置" + IocXmlRules.SNAN_RULE.getType() + "的属性");
                    }
                    //根据包路径初始化
                    ScanUtil.initInstanceSet(packageName);
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new ClassCastException("类无法加载异常");
        }
    }
}
